package school.emm;

import android.content.Intent;

public class Protocol {
	private boolean Established_;
	private boolean chatRoomInit_;
	private boolean truckerSpotInit_;
	private String processedMessage_;
	private char header_;
	private CommunicateWithServer comThread_;
	private String userid_;
	
	public Protocol(CommunicateWithServer comThread) {
		Established_ = false;
		chatRoomInit_ = false;
		truckerSpotInit_ = false;
		this.comThread_ = comThread;
	}

	public String init(String message) {
		if(!Established_) {
			this.userid_ = message;
			Established_ = true;
			return "0";
		} else if (!chatRoomInit_) {
			chatRoomInit_ = true;
			return "0";
			
		} else if (!truckerSpotInit_) {
			truckerSpotInit_ = true;
			return "Initialized";
		}
		return "This will never happen.";
	}
	public void processMessage(String message) {
			header_ = message.charAt(0);
			switch (header_) {
			case '0':
				// Will never happen for client -> server
				break;
			case '1':
				// Recieves a chat message
				handleChatMessage(message);
				break;
			case '2':
				// Recieved create a chat room message
				handleCreateChatroom(message);
				break;
			case '3':
				// Join a chat room
				//processedMessage_ = handleJoinChatroomMessage(message);
				break;
			case '4':
				// Call method to handle header == 4
				break;
			case '5':
				// Call method to handle header == 5
				break;
			case '6':
				// Call method to handle header == 6
				break;
			case '7':
				// Call method to handle header == 7
				break;
			case '8':
				// Call method to handle header == 8
				break;
			case '9':
				// Call method to handle header == 9
				break;
			default:
				break;
			}
	}
	
	
	public String getUserid() {
		return this.userid_;
	}
	
	public void handleChatMessage(String message) {
		String [] msgParts = message.split(";");
		comThread_.getEmm().recievedChatMessage(msgParts[1]);
	}
	
	private void handleCreateChatroom(String message){
		String[] msgParts = message.split(";");
		if(msgParts.length == 2){
			comThread_.getEmm().setChatId(Integer.parseInt(msgParts[1]));
			System.out.println(msgParts[1]);
		} else {
			String chatId = msgParts[1];
			String categoryId = msgParts[2];
			String topic = msgParts[3];
			String x = msgParts[4];
			String y = msgParts[5];
			comThread_.getEmm().createChatRoomOnMap(topic, Integer.parseInt(categoryId), Integer.parseInt(x), Integer.parseInt(y), Integer.parseInt(chatId));
		}
	}
	

}
